
$(function () {
    scrollBackTop();
    leftTags.init();
    centerTemplate.init();
    centerTemplate.hoverShowBtn();

    $(document).on('click', '.m-style-ul>li', function () {
        leftTags.setStyle(this);
    });

    $(document).on('click', '.m-place-ul>li', function () {
        leftTags.setScene(this);
    });

    $(document).on('click', '.m-color-ul>li', function () {
        leftTags.setColor(this);
    });

    $(window).scroll(function () {
        var _scrollTop = centerTemplate.scrollTop();
        var _windowHeight = centerTemplate.windowHeight();
        var _documentHeight = centerTemplate.documentHeight();
        
        if(_scrollTop > 0){
            if(_scrollTop + _windowHeight >= _documentHeight){
                centerTemplate.loadData();
            }
        }
    });
});

var leftTags = {
    init: function () {
        templateRequest.getAllTags({}, function (res) {
            var _data = res.data;
            $styleTagsUl = $("#style_tags_ul");
            $colorTagsUl = $("#color_tags_ul");
            $sceneTagsUl = $("#scene_tags_ul");
            for (var i in _data[1]) {
                $styleTagsUl.append("<li data-type=" + _data[1][i]['type'] + " data-index=" + _data[1][i]['power_index'] + ">" + _data[1][i]['name'] + "</li>");
            }
//            for(var j in _data[2]){
//                $colorTagsUl.append("<li>"+_data[2][j]['name']+"</li>");
//            }            
            for (var k in _data[3]) {
                $sceneTagsUl.append("<li data-type=" + _data[3][k]['type'] + " data-index=" + _data[3][k]['power_index'] + ">" + _data[3][k]['name'] + "</li>");
            }
        });
    },
    setStyle: function (_this) {
        $(_this).addClass('orange').siblings().removeClass('orange');
        var _type = $(_this).attr("data-type");
        var _index = $(_this).attr("data-index");
        centerTemplate.condition.style = _index;
        centerTemplate.loadData(true);
    },
    setScene: function (_this) {
        $(_this).addClass('orange').siblings().removeClass('orange');
        var _type = $(_this).attr("data-type");
        var _index = $(_this).attr("data-index");
        centerTemplate.condition.scene = _index;        
        centerTemplate.loadData(true);
    },
    setColor: function (_this) {
        $(_this).addClass('orange').siblings().removeClass('orange');
        var _type = $(_this).attr("data-type");
        var _index = $(_this).attr("data-index");
        centerTemplate.condition.color = _index;             
        centerTemplate.loadData(true);
    }
};

var centerTemplate = {
    nextPage: 1,
    hasMore:true,
    currentId: 0,
    defaultThumb:"http://img.huodongju.com/www/invitation/thumb_1005_20170823.png",
    status:0,
    condition:{style:'',color:'',scene:''},
    init: function () {
        this.loadData();
    },
    loadData: function (reload) {
        layer.closeAll();
        if(centerTemplate.status == 1){
            return false;
        }
        // var loadingIndex = layer.load();
        reload = reload || false;
        if(reload){
            centerTemplate.hasMore = true;   
            centerTemplate.nextPage = 1;
            $("#template_list_ul .m-model-li").remove();
        }
        if(centerTemplate.hasMore == false){
            $('.m-center .nomore-template').show();
            // layer.msg("没有更多模板了");
            // layer.close(loadingIndex);
            return false;
        }
        $("#loading_more").show();
        
        var _option = centerTemplate.condition;
        _option.page = centerTemplate.nextPage;
        templateRequest.getTemplateList(_option, function (res) {
           centerTemplate.status = 1;
            if(res.data.rows == null){
                centerTemplate.hasMore = false;
                $('.m-center .nomore-template').show();
                // layer.msg("没有更多模板了");
                $("#loading_more").hide();
            }else{
                var _list = res.data.rows;
                var _liHtml = '';
                var _thumb = '';
                for (var i in _list) {
                    if (_list[i]['thumb'] == '') {
                        _thumb = centerTemplate.defaultThumb;
                    } else {
                        _thumb = _list[i]['thumb'];
                    }
                    _liHtml += '<li class="m-model-li" data-id="' + _list[i]['id'] + '"><img src="' + _thumb + '" alt=""><div class="m-model-title">' + '<p title="'+ _list[i]['title'] +'">' + _list[i]['title'] + '</p>'  + '</div></li>';
                }
                $("#template_list_ul").append(_liHtml);
                centerTemplate.nextPage = parseInt(res.data.currpage || 0) + 1;
                $("#loading_more").hide();
            }
           centerTemplate.status = 0;
        });
        // layer.close(loadingIndex);
    },
    hoverShowBtn: function () {
        var _html = "" +
                "<div class='m-model-shade'>" +
            "<button onclick='centerTemplate.useThis(this);' class='btn-f66926'>立即使用</button>" +
            "<button onclick='centerTemplate.preview(this);' class='btn-f66926' style='background-color: white!important;color: #f66926!important;border: 1px solid white!important;'>点击预览</button>" +
                "</div>";

        $(document).on("mouseenter", ".m-model-li", function () {
            $(this).append(_html);
            $(this).siblings().find('.m-model-shade').remove();
        }).on("mouseleave", '.m-model-li', function () {
            $(this).find('.m-model-shade').remove();
        });
    },
    preview: function (_previewBtn) {
        var layWidth;
        var winWidth = $(window).width();
        if(winWidth > 1500){
            layWidth = 450 + 'px';
        }else {
            layWidth = 300 + 'px';
        }
        var _id = $(_previewBtn).closest("li").attr("data-id");
        this.currentId = _id;
        var _html = $('.lay-template-preview');
        layer.open({
            type: 1,
            skin: 'lay-temp-preview', //加上边框
            area: [layWidth, '95%'], //宽高
            content: _html,
            title:false,
            closeBtn:3,
            shade:0.8,
            shadeClose:true,
            success:function (layero, index) {
                var loadingIndex = layer.load();
               $(layero).find('.lay-temp-iframe-box>iframe').remove();
               $(layero).find('.lay-temp-iframe-box').append('<iframe src="/Studio/templateDetail?id=' + _id + '" frameborder="0"></iframe>');
               $(layero).find('.lay-temp-use-btn').on('click',function () {
                   centerTemplate.openEditPage(_id);
                });
                layer.close(loadingIndex);
            },
            cancel:function(index, layero){
               $(layero).find('.lay-temp-iframe-box>iframe').remove();
            },
            scrollbar:false
        });
    },
    openEditPage: function (_id) {
        var loadingIndex = layer.load();
        if (_id == '' || _id == 'undefined' || _id == 0 || _id == null) {
            window.location.href = "/Studio/index";
        } else {
            window.location.href = '/Studio/index?tId=' + _id;
        }
        layer.close(loadingIndex);
    },
    useThis: function (_useBtn) {
        var _id = $(_useBtn).closest("li").attr("data-id");
        centerTemplate.openEditPage(_id);
    },
    useThisAll: function () {
        if (this.currentId == 0) {
            layer.msg("请先点击左侧模板");
            return false;
        }
        centerTemplate.openEditPage(this.currentId);
    },
    scrollTop: function () {
        return Math.max(
                //chrome
                document.body.scrollTop,
                //firefox/IE
                document.documentElement.scrollTop);
    },
    documentHeight: function () {
        //现代浏览器（IE9+和其他浏览器）和IE8的document.body.scrollHeight和document.documentElement.scrollHeight都可以
        return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
    },
    windowHeight: function () {
        return (document.compatMode == "CSS1Compat") ?
                document.documentElement.clientHeight :
                document.body.clientHeight;
    }
};

//滚动条美化
function niceScroll(_id,fixed,_top) {
    $(_id).niceScroll({
        cursorcolor: "#ccc",//#CC0071 光标颜色
        cursoropacitymax: 1, //改变不透明度非常光标处于活动状态（scrollabar“可见”状态），范围从1到0
        touchbehavior: false, //使光标拖动滚动像在台式电脑触摸设备
        cursorwidth: "5px", //像素光标的宽度
        cursorborder: "0", // 	游标边框css定义
        cursorborderradius: "5px",//以像素为光标边界半径
        autohidemode: false, //是否隐藏滚动条
        fixedTop:_top,
    });
    $(_id).getNiceScroll().resize();
    var position = fixed || null;
    if(position != null){
        var _Id = $(_id).getNiceScroll()[0].id;
        $('#' + _Id).css({'position':fixed});
    }
}